package com.flutter_ecg.flutter_ecg.ecgapplication.ecgreportview;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Environment;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.ikinloop.iklibecgcheck.IKEcgCheck;
import com.flutter_ecg.flutter_ecg.R;
import com.flutter_ecg.flutter_ecg.ecgapplication.utils.Constants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
    该页面类实现了心电图报告的回显功能。要求在页面启动时传入2个参数：心电报告文件路径和对应心电图的智能分析结果。
    流程描述： 当传入参数并启动该页面后，系统会解压心电报告文件，读取并绘制心电数据，同时也会显示心电图的智能分析结果。

 */
public class EcgReportActivity extends AppCompatActivity {

    private final String TAG = "EcgReportActivity:::";

    private RelativeLayout reportBackLayout;
    private ImageView reportBack;
    private IKEcgReportLayout ikEcgReportLayout;
    private String detectTime;

    private String ecgTarFilePath = "";

    private IKEcgCheck ikEcgCheck;

    private boolean isScreenland = false;
    private int[] ecgData;
    private int[] ecgEcgState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ecg_report);

        final Intent intent = getIntent();
        ecgTarFilePath = intent.getStringExtra(Constants.TARTFILEPATH_KEY);
        Log.i(TAG, "ecgTarFilePath:::" + ecgTarFilePath);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        detectTime = sdf.format(new Date(Long.parseLong(String.valueOf(System.currentTimeMillis()))));

        reportBackLayout = (RelativeLayout) findViewById(R.id.reportBackLayout);
        reportBack = (ImageView) findViewById(R.id.reportBack);
        reportBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ikEcgReportLayout = (IKEcgReportLayout) findViewById(R.id.report_layout);
        ikEcgReportLayout.initEcgReportLayout();
        ikEcgReportLayout.getFullScreenIv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setScreenOritation();
            }
        });

        initIKEcgLib();
        unpackEcgData();

        initResultData();
    }

    /**
     * Initialization IKLibrary
     */
    private void initIKEcgLib() {
        if (null == ikEcgCheck) {
            ikEcgCheck = IKEcgCheck.getInstance(EcgReportActivity.this);
        }
    }

    private void unpackEcgData() {
        if (TextUtils.isEmpty(ecgTarFilePath) || !ecgTarFilePath.endsWith(".tar")) {
            return;
        }
        //ecgFileDirPath is the unpack dir path of tar
        String ecgFileDirPath = ecgTarFilePath.substring(0, ecgTarFilePath.length() - 4);
        File ecgFileDir = new File(ecgFileDirPath);
        Log.i(TAG, "unpackEcgData:::" + ecgFileDir.exists() + ":::length:" + ecgFileDir.length());
        int ecgDataLength = 0;
        if (!ecgFileDir.exists()) {
            ecgDataLength = ikEcgCheck.IKUnPackEcgDataFile(ecgTarFilePath, ecgData);
        } else {
            ecgDataLength = ikEcgCheck.IKEcgAnalyzeSdkGetEcgDataLength(ecgFileDirPath);
        }
        if (ecgDataLength <= 0) {
            return;
        }
        ecgData = new int[ecgDataLength];
        ecgEcgState = new int[ecgDataLength];
        ikEcgCheck.IKecgAnalyzeSdkGetEcgDataFromFile(ecgFileDirPath, ecgDataLength, ecgData, ecgEcgState);
        ikEcgReportLayout.setEcgData(ecgData, ecgEcgState);
    }

    private void initResultData() {
        Intent intent = getIntent();
        String ecgSmartResult = intent.getStringExtra(Constants.ECGRESMARTSULT_KEY);
        Log.i(TAG, "ecgSmartResult:::" + ecgSmartResult);

        ikEcgReportLayout.setDetectTime(detectTime);
        ikEcgReportLayout.setDuration(40);

        if (TextUtils.isEmpty(ecgSmartResult)) {
            return;
        }

        JSONArray ecgSympJsonArray = null;
        JSONObject ecgValObj = null;
        try {
            JSONObject ecgSmartResultObj = new JSONObject(ecgSmartResult);
            ecgSympJsonArray = ecgSmartResultObj.getJSONArray("ecgsymps");//获取数组
            ecgValObj = ecgSmartResultObj.getJSONObject("ecgval");
            Log.i(TAG, ecgValObj.getString("breath"));
            Log.i(TAG, ecgValObj.getString("hrmean"));
            ikEcgReportLayout.setHrValue(ecgValObj.getString("hrmean"));
            ikEcgReportLayout.setBreathValue(ecgValObj.getString("breath"));
            ikEcgReportLayout.setPressureValue(ecgValObj.getString("pressure"));

            List<String> suggestionList = new ArrayList<>();
            List<String> sympNameList = new ArrayList<>();
            for (int i = 0; i < ecgSympJsonArray.length(); i++) {
                Log.i(TAG, i + ":::" + ecgSympJsonArray.get(i).toString());
                JSONObject ecgSympObj = ecgSympJsonArray.getJSONObject(i);
                suggestionList.add(ecgSympObj.getString("suggestion"));
                sympNameList.add(ecgSympObj.getString("name"));
            }
            ikEcgReportLayout.setAnalyzeResult(sympNameList);
            ikEcgReportLayout.setSuggest(suggestionList);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置屏幕的横竖屏
     */
    private void setScreenOritation() {
        if (isScreenland) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            isScreenland = true;
            reportBackLayout.setVisibility(View.GONE);
        } else {
            isScreenland = false;
            reportBackLayout.setVisibility(View.VISIBLE);
        }
        ikEcgReportLayout.onConfigureChanged(newConfig.orientation);
    }
}
